package com.koron.configure.workflow.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koron.bean.util.RedisUtils;
import com.koron.common.core.business.configsettings.utils.ConfigInfoTool;
import com.koron.common.core.business.workflow.bean.po.ConfigureWorkflow;
import com.koron.common.core.business.workflow.bean.properties.WorkFlowConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 对接工作流引擎
 *
 * @author jzp
 * @since 2022/1/24
 */
@Service
@Slf4j
public class WorkflowEngineService {

    @Autowired
    private WorkFlowConfigProperties workFlowConfigProperties;

    /**
     * 登录工作流引擎，获取token
     */
    private void login() {
        Map<String, String> config = ConfigInfoTool.getConfigByCode("common", "workflow");
        JSONObject json = new JSONObject();
        json.put("account", config.get("username"));
        json.put("password", config.get("password"));

        String loginUrl = config.get("url") + "/login.htm";
        log.info("登录工作流，url：{}，参数：{}", loginUrl, json);
        String response = HttpRequest.post(loginUrl).body(json.toJSONString()).execute().body();
        JSONObject resultObject = JSONObject.parseObject(response);
        if (resultObject.getInteger("code") == -1) {
            throw new IllegalArgumentException("工作流用户名密码错误："+resultObject.getString("description"));
        }
        RedisUtils.set("workflow_token", resultObject.getString("data"));
    }

    private String getToken() {
        Object workflow_token = RedisUtils.get("workflow_token");
        if (workflow_token == null) {
            login();
        }
        return RedisUtils.get("workflow_token").toString();
    }

    /**
     * 根据应用编号获取工作流模板组数据
     */
    public List<ConfigureWorkflow> listSetCode(String appCode) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", 1);
        map.put("pageSize", 100);

        String url = workFlowConfigProperties.getUrl() + "/process/queryDesignProcessList.htm?" + HttpUtil.toParams(map);
        log.info("获取工作流模板组，url：{}，参数：{}", url, map);

        String response = HttpRequest.get(url).cookie(new HttpCookie("token", getToken())).timeout(-1).execute().body();
        JSONObject resultObject = JSONObject.parseObject(response);
        int code = resultObject.getInteger("code");
        if (code == -1) {
            throw new IllegalArgumentException("工作流错误："+resultObject.getString("description"));
        } else if (code == 10000) {
            login();
            response = HttpRequest.get(url).cookie(new HttpCookie("token", getToken())).timeout(-1).execute().body();
            resultObject = JSONObject.parseObject(response);
        }
        JSONArray data = resultObject.getJSONArray("data");
        JSONArray sets = null;
        for (int i = 0; i < data.size(); i++) {
            String appCode1 = data.getJSONObject(i).getString("appCode");
            if (StrUtil.equals(appCode, appCode1)) {
                sets = data.getJSONObject(i).getJSONArray("sets");
                break;
            }
        }
        if (CollUtil.isEmpty(sets)) {
            throw new IllegalArgumentException("当前租户没有工作流模板组数据");
        }

        List<ConfigureWorkflow> configureWorkflowList = new ArrayList<>();
        for (int i = 0; i < sets.size(); i++) {
            JSONObject jsonObject = sets.getJSONObject(i);
            ConfigureWorkflow configureWorkflow = new ConfigureWorkflow();
            configureWorkflow.setId(jsonObject.getString("setId"));
            configureWorkflow.setSetCode(jsonObject.getString("setCode"));
            configureWorkflow.setModuleCode(jsonObject.getString("setName"));
            configureWorkflow.setAppCode(appCode);
            configureWorkflowList.add(configureWorkflow);
        }
        return configureWorkflowList;
    }

    /**
     * 根据模板组id获取改模板组下的所有模板
     * @param setId ConfigureWorkflow.id
     */
    public List<ConfigureWorkflow> listProcessCode(String setId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", 1);
        map.put("pageSize", 100);
        map.put("setId", setId);

        String url = workFlowConfigProperties.getUrl() + "/process/queryForList.htm?" + HttpUtil.toParams(map);
        log.info("获取工作流模板组，url：{}，参数：{}", url, map);
        String response = HttpRequest.get(url).cookie(new HttpCookie("token", getToken())).timeout(-1).execute().body();
        JSONObject resultObject = JSONObject.parseObject(response);
        int code = resultObject.getInteger("code");
        if (code == -1) {
            throw new IllegalArgumentException("工作流错误："+resultObject.getString("description"));
        } else if (code == 10000) {
            login();
            response = HttpRequest.get(url).cookie(new HttpCookie("token", getToken())).timeout(-1).execute().body();
            resultObject = JSONObject.parseObject(response);
        }
        JSONObject data = resultObject.getJSONObject("data");
        JSONArray list = data.getJSONArray("list");

        List<ConfigureWorkflow> configureWorkflowList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject jsonObject = list.getJSONObject(i);
            ConfigureWorkflow configureWorkflow = new ConfigureWorkflow();
            configureWorkflow.setAppCode(jsonObject.getString("appCode"));
            configureWorkflow.setSetCode(jsonObject.getString("setCode"));
            configureWorkflow.setProcessCode(jsonObject.getString("code"));
            configureWorkflow.setProcessName(jsonObject.getString("name"));
            configureWorkflowList.add(configureWorkflow);
        }
        return configureWorkflowList;
    }

}
